import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from '../user/user.service';
import * as bcrypt from 'bcrypt';
import { CreateUserDto } from '../user/dto/user.dto';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {}

  async validateUser(
    username: string,
    password: string,
  ): Promise<Pick<CreateUserDto, 'username' | 'password' | 'id'>> {
    if (!username || !password) {
      throw new UnauthorizedException('用户名和密码不能为空');
    }
    const user = await this.userService.findOne(username);
    console.log(user, 'userd');
    if (!user || !user.id) {
      throw new UnauthorizedException('用户不存在');
    }

    if (!user.password) {
      throw new UnauthorizedException('用户数据异常，请联系管理员');
    }

    const isValid = await bcrypt.compare(password, user.password);
    if (!isValid) {
      throw new UnauthorizedException('密码错误');
    }

    return { username, password, id: user.id };
  }

  async login(credentials: { username: string; password: string }) {
    const user = await this.validateUser(
      credentials.username,
      credentials.password,
    );
    console.log(user, '----user---');
    const payload = { username: user.username, req: user.id };
    return {
      access_token: this.jwtService.sign(payload),
      auths: ['*', 'member', 'lowcode', 'addlowcode'],
    };
  }

  async getUserInfo(token: string) {
    try {
      const decoded = this.jwtService.verify(token);
      const { username } = decoded as { username: string };
      const user = await this.userService.findOne(username);
      if (!user) {
        throw new UnauthorizedException('用户不存在');
      }
      // 返回用户信息时排除password字段
      const { password: _, ...result } = user;
      return result;
    } catch (error) {
      throw new UnauthorizedException('无效的令牌');
    }
  }
}
